package com.xixi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xixi.entity.Product;
import com.xixi.entity.ProductImage;
import com.xixi.mapper.ProductImageMapper;
import com.xixi.mapper.ProductMapper;
import com.xixi.mapper.UserMapper;
import com.xixi.pojo.dto.ProductDTO;
import com.xixi.pojo.query.ProductQueryPage;
import com.xixi.pojo.vo.ProductVO;
import com.xixi.pojo.vo.Result;
import com.xixi.service.ProductService;
import com.xixi.service.UserService;
import com.xixi.utils.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductImageMapper productImageMapper;

    @Autowired
    private FileUploadUtil fileUploadUtil;
    @Autowired
    private UserMapper userMapper;
    @Transactional
    @Override
    public IPage<ProductVO> page(ProductQueryPage queryPage) {
        IPage<ProductVO> page = new Page<>(queryPage.getPageNum(), queryPage.getPageSize());
        IPage<ProductVO> productPage = productMapper.page(page, queryPage);
        for (ProductVO product : productPage.getRecords()) {
            List<String> images = productImageMapper.selectImagesByProductId(product.getId());
            product.setImages(images);
        }
        return productPage;
    }

    @Override
    public Result delete(List<Integer> ids) {
        if(productMapper.deleteBatchIds(ids) > 0){
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }
    @Override
    public void uploadProductImages(Integer productId, List<MultipartFile> files) throws Exception {
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            String imagePath = fileUploadUtil.uploadImage(file);
            ProductImage image = new ProductImage();
            image.setProductId(productId);
            image.setImageUrl(imagePath);
            image.setSortOrder(i);
            image.setCreateTime(LocalDateTime.now());
            //log.info("image:{}", image);
            productImageMapper.insert(image);
        }
    }

    @Override
    public List<String> getCategory() {
        List<String> category = productMapper.getCategory();
        return category;
    }

    @Override
    @Transactional
    public Result insert(ProductDTO productDTO) {
        Integer categoryId = productMapper.getCategoryIdByName(productDTO.getCategory());
        Integer userId = userMapper.getUserIdNyName(productDTO.getName());
        productDTO.setUserId(userId);
        productDTO.setCategoryId(categoryId);
        //log.info("productDTO:{}", productDTO);
        Product product = BeanUtil.toBean(productDTO, Product.class);
        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());
        if(productMapper.insert(product) > 0){
            // 返回新创建的商品ID
            return Result.success("添加成功", product.getId());
        }
        return Result.error("添加失败");
    }

    @Override
    public Result update(ProductDTO productDTO) {
        Product product = BeanUtil.toBean(productDTO, Product.class);
        product.setUpdateTime(LocalDateTime.now());
        if(productMapper.updateById(product) > 0){
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }

    @Override
    public List<ProductVO> list() {
        List<ProductVO> list = productMapper.list();
        return list;
    }

    @Override
    public List<ProductVO> productListById(Integer id) {
        List<ProductVO> list = productMapper.productListById(id);
        for (ProductVO productVO : list) {
            productVO.setImages(getProductImageUrl(productVO.getId()));
        }
        return list;
    }
    @Transactional
    @Override
    public Result publish(ProductDTO productDTO) {
        Integer categoryId = productMapper.getCategoryIdByName(productDTO.getCategory());
        productDTO.setCategoryId(categoryId);
      //  log.info("productDTO:{}", productDTO);
        Product product = BeanUtil.toBean(productDTO, Product.class);
        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());
        if(productMapper.insert(product) > 0){
            // 返回新创建的商品ID
            return Result.success("发布成功", product.getId());
        }
        return Result.error("发布失败");
    }

    @Override
    public ProductVO getProductById(Integer id) {
        ProductVO productVO = productMapper.getProductById(id);
        productVO.setImages(getProductImageUrl(id));
        return productVO;
    }
    public List<String> getProductImageUrl(Integer id) {
        List<ProductImage> images = productImageMapper.selectByProductId(id);
        List<String> imageUrls = new ArrayList<>();
        for (ProductImage image : images) {
            imageUrls.add(image.getImageUrl());
        }
        return imageUrls;
    }
}
